#include "GAF_Timer.h"
#include "GAF_Platform.h"

namespace GAF
{
// 	Timer::TimerList Timer::ms_lstTimers;
// 	Timer::TimerList Timer::ms_lstExactTimers;
// 	unsigned int Timer::NameID = 0;

	void Timer::AddTimer(Timer* pTimer)
	{
		void* _plstTimers = (void*)GAF_pTHEAPP->GetTimers();
		GAF_pTHEAPP->GetTimers()->push_back(pTimer);
	}

	void Timer::RemoveTimer(Timer* pTimer)
	{
		GAF_pTHEAPP->GetTimers()->remove(pTimer);
		GAF_pTHEAPP->GetExactTimers()->remove(pTimer);
	}

	void Timer::UpdateTimers()
	{
		void* _plstTimers = (void*)GAF_pTHEAPP->GetTimers();

		static TimerList::const_iterator _cit;
		for(_cit = GAF_pTHEAPP->GetTimers()->begin();
			_cit != GAF_pTHEAPP->GetTimers()->end(); _cit++)
		{
			(*_cit)->Update();
		}
	}

	void Timer::UpdateExactTimers()
	{
		static TimerList::const_iterator _cit;
		for(_cit = GAF_pTHEAPP->GetExactTimers()->begin();
			_cit != GAF_pTHEAPP->GetExactTimers()->end(); _cit++)
		{
			(*_cit)->Update();
		}
	}



	Timer::Timer()
	{
// 		static char szID[5];
// 		SYS_SPRINTF(szID, "Timer_%d", NameID++);
// 
// 		m_strName	= szID;
		m_ttSave	= 0;
		m_isRun		= false;

		AddTimer(this);
	}

// 	Timer::Timer(STD_STRING strName) :
// 		m_strName(strName),
// 		m_ttSave(0),
// 		m_isRun(false)
// 	{
// 		AddTimer(this);
// 	}

	Timer::~Timer()
	{
		RemoveTimer(this);
	}

	void Timer::Exact()
	{
		GAF_pTHEAPP->GetTimers()->remove(this);
		GAF_pTHEAPP->GetExactTimers()->push_back(this);
	}

	bool Timer::Start(TimeTicks ttInterval)
	{
		if(ttInterval > 0)
			SetInterval_a(ttInterval);

		m_isRun = true;
		m_ttSave = GAF_pTHEPLATFORM->GetTimeTicks();
		return true;
	}

	void Timer::Stop()
	{
		m_isRun = false;
	}

	void Timer::Update()
	{
		static TimeTicks ttTime;

		if(m_isRun)
		{
			ttTime = GAF_pTHEPLATFORM->GetTimeTicks();
			if(ttTime - m_ttSave >= ATTRIB(Interval))
			{
				// 如果不继续，停止计时
// 				if(OnRunTimer() == false && m_isRun)
// 					Stop();

				OnRunTimer();

				if(m_isRun)
					m_ttSave = ttTime;
			}
		}
	}

	void Timer::OnRunTimer()
	{
		if(GetRunClass_a() != NULL)
			GetRunClass_a()->OnRun(this);
	}

	bool Timer::IsRun()
	{
		return m_isRun;
	}

}
